#include "Anx_RTT.h"

#include "FreeRTOS.h"
#include "task.h"

#include "main.h"

char TxBuf[256];
char buffer[224];
int Timernal_Num = 0;


void Anx_RTT(char level, const char* tag, const char* format, ...)
{
    int len = 0;

    va_list args;
    va_start(args, format);
    len = vsnprintf(buffer, (sizeof(buffer)), format, args);
    va_end(args);
    if (len >= 64 || len < 0)
        return;

    switch (level)
    {
    case level_trace:
        len = snprintf(TxBuf, 96, "[%s] %s\r\n", tag, buffer);
        break;
    case level_log:
        len = snprintf(TxBuf, 96, "[LOG][%s] %s\r\n", tag, buffer);
        break;
    case level_war:
        len = snprintf(TxBuf, 96, "[WAR][%s] %s\r\n", tag, buffer);
        break;
    case level_err:
        len = snprintf(TxBuf, 96, "[ERR][%s] %s\r\n", tag, buffer);
        break;
    default:
        len = 0;
        break;
    }
    if (len >= 96 || len < 0)
        return;

    taskENTER_CRITICAL();
    SEGGER_RTT_Write(0, TxBuf, len);
    taskEXIT_CRITICAL();

    // taskEXIT_CRITICAL();
}



void Anx_RTT_ISR(const char* str)
{
    if (__get_IPSR() != 0U) // 中断中
    {
        uint32_t previous_interrupt_mask = taskENTER_CRITICAL_FROM_ISR();
        SEGGER_RTT_Write(0, str, strlen(str));
        taskEXIT_CRITICAL_FROM_ISR(previous_interrupt_mask);
    }
}
